package com.vueblog.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vueblog.common.Result;
import com.vueblog.common.form.LoginInfo;
import com.vueblog.entity.MUser;
import com.vueblog.service.IMUserService;
import com.vueblog.shiro.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
public class AccountController {

    @Autowired
    private IMUserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @RequestMapping("/login")
    public Result login(@Validated @RequestBody LoginInfo loginForm, HttpServletResponse res) {
        MUser user = userService.getOne(new QueryWrapper<MUser>().eq("username", loginForm.getUser()));
        Assert.notNull(user, "用户不存在");
        String pwdMd5 = SecureUtil.md5(loginForm.getPwd());
        if(!user.getPassword().equals(pwdMd5)) {
            return Result.fail("密码错误");
        }
        if(user.getStatus()==null) {
            return Result.fail("账号状态异常");
        }else if(user.getStatus()==1) {
            return Result.fail("账号已注销");
        }
        String jwt = jwtUtils.generateToken(user.getId());
        res.setHeader(jwtUtils.getHeaderKey(), jwt);
        res.setHeader("Access-Control-Expose-Headers", jwtUtils.getHeaderKey());
        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map()
        );
    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }

}
